import path from 'path'
import fs from 'fs'
import express from 'express'
import cors from 'cors'

const root = process.cwd()

// https://www.expressjs.com.cn/
const app = express()
app.use(cors())

app.use(express.static(path.resolve(root, 'public')))

let rc = fs.readFileSync(
    path.resolve(
        process.cwd(),
        'public/test.pdf'
    )
)
console.log(rc)

// https://blog.csdn.net/qq_43586648/article/details/126894378
// 微信公众号内下载pdf等文件，受微信所限制，安卓和IOS不同处理方式（最最最优版）

// https://juejin.cn/post/7052946931194003463
// 基于nodejs 的几种http文件传输方案实践

app.use('/download/pdf', (req, res) => {
    res.writeHead(200, {
        "Content-Disposition": "attachment;fileName=XXXX.pdf"
    });

    const buffer = fs.readFileSync(
        path.resolve(
            process.cwd(),
            'public/test.pdf'
        )
    )
    console.log(buffer)
    res.write(buffer);
    res.end();
})

function start() {
    const PORT = 10086
    const HOST = '127.0.0.1'
    app.listen(PORT, err => {
        if (err) {
            console.error('start error', err?.message)
            throw err;
        }
        console.log(`start http://${HOST}:${PORT}`)
    })
}

start()
